import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/util/boss_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NavigatorManager extends NavigatorObserver {
  factory NavigatorManager() => _getInstance();

  static NavigatorManager _getInstance() {
    if (_instance == null) {
      _instance = NavigatorManager._internal();
    }

    return _instance;
  }

  static NavigatorManager get instance => _getInstance();
  static NavigatorManager _instance;

  NavigatorManager._internal() {
    _mRoutes = [];
  }

  // 当前路由栈
  static List<Route> _mRoutes;

  List<Route> get routes => _mRoutes;

  // 当前路由
  Route get currentRoute => _mRoutes.length == 0 ? null : _mRoutes.last;

  //用来路由跳转
  NavigatorState get mNavigator => currentRoute?.navigator;

  // 当调用Navigator.push时回调
  @override
  void didPush(Route route, Route previousRoute) {
    super.didPush(route, previousRoute);

    hideLoadingToast();

    if (_mRoutes == null) {
      _mRoutes = new List<Route>();
    }

    // 这里过滤调push的是dialog的情况
    if (route is CupertinoPageRoute || route is MaterialPageRoute) {
      print('当前页面：${currentRoute?.settings?.name}');

      _mRoutes.add(route);
    }
  }

  // 当调用Navigator.replace时回调
  @override
  void didReplace({Route newRoute, Route oldRoute}) {
    super.didReplace();

    if (newRoute is CupertinoPageRoute || newRoute is MaterialPageRoute) {
      _mRoutes.remove(oldRoute);
      _mRoutes.add(newRoute);
    }
  }

  // 当调用Navigator.pop时回调
  @override
  void didPop(Route route, Route previousRoute) {
    super.didPop(route, previousRoute);

    BossUtils.tryLostFocus(route.navigator.context);

    hideLoadingToast();

    if (route is CupertinoPageRoute || route is MaterialPageRoute) {
      print('当前页面：${currentRoute?.settings?.name}');

      _mRoutes.remove(route);
    }
  }

  @override
  void didRemove(Route removedRoute, Route oldRoute) {
    super.didRemove(removedRoute, oldRoute);

    if (removedRoute is CupertinoPageRoute || removedRoute is MaterialPageRoute) {
      _mRoutes.remove(removedRoute);
    }
  }
}
